﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using BrightIdeasSoftware;
using GDFlacTool.Common;

namespace GDFlacTool.Forms
{
    public partial class FormArtistGenre : Form
    {
        private readonly ArtistGenreHelper _artistGenreHelper;
        private readonly TypedObjectListView<ArtistGenre> _artistGenreList;
        private List<ArtistGenre> _artistGenres;

        public FormArtistGenre(ArtistGenreHelper artistGenreHelper)
        {
            InitializeComponent();

            _artistGenreHelper = artistGenreHelper;
            _artistGenreList = new TypedObjectListView<ArtistGenre>(objectListView);
            _artistGenres = _artistGenreHelper.GetAllArtistGenre();
        }

        private void FormArtistGenre_Load(object sender, EventArgs e)
        {
            SetObjects();
        }

        private void SetObjects()
        {
            if (_artistGenres != null)
            {
                olvColumnId.AspectToStringConverter = delegate(object x)
                {
                    int index;
                    if (Int32.TryParse(x.ToString(), out index))
                    {
                        return String.Format("{0:0000#}", index);
                    }

                    return String.Empty;
                };

                objectListView.SetObjects(_artistGenres);

                lblNumberOfArtists.Text = string.Format("Number of artists: {0}", _artistGenres.Count);
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            var frm = new FormArtistGenreNew(_artistGenreHelper.FindNextId(), _artistGenreHelper.GetAllArtistGenre());

            DialogResult result = frm.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                if (!_artistGenreHelper.IsArtistInList(frm.ArtistGenre.Artist))
                {
                    _artistGenres.Add(frm.ArtistGenre);
                    
                    objectListView.SetObjects(_artistGenres);
                    
                    btnOK.Enabled = true;
                }
                else
                {
                    string msg = string.Format("The artist '{0}' is already in the Artist/Genre collection, no new row was added!", frm.ArtistGenre.Artist);

                    MessageBox.Show(this, msg, @"Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (_artistGenreList.SelectedObjects.Count == 1)
            {
                var frm = new FormArtistGenreEdit(_artistGenreList.SelectedObject, _artistGenreHelper.GetAllArtistGenre());

                DialogResult result = frm.ShowDialog(this);

                if (result == DialogResult.OK)
                {
                    objectListView.SetObjects(_artistGenres);

                    btnOK.Enabled = true;
                }
            }

            objectListView.Focus();

            if (_artistGenreList.SelectedObjects.Count != 1)
            {
                btnEdit.Enabled = false;
                btnRemove.Enabled = false;
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (_artistGenreList.SelectedObject != null)
            {
                string msg = string.Format("Are you sure you want to remove the following artist?\n\n{0}", _artistGenreList.SelectedObject.Artist);

                DialogResult result = MessageBox.Show(this, msg, @"Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

                if (result == DialogResult.OK)
                {
                    if (_artistGenres.Contains(_artistGenreList.SelectedObject))
                    {
                        _artistGenreList.SelectedObject.Status = ArtistGenreStatus.Remove;

                        objectListView.SetObjects(_artistGenres);

                        btnOK.Enabled = true;
                    }   
                }
            }
        }

        private void objectListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (_artistGenreList.SelectedObjects.Any())
            {
                btnEdit.Enabled = true;
                btnRemove.Enabled = true;
            }
            else
            {
                btnEdit.Enabled = false;
                btnRemove.Enabled = false;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            btnOK.Enabled = false;

            _artistGenreHelper.UpdateAllArtistGenre(_artistGenres);
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string date = DateTime.Now.ToShortDateString();
                string time = DateTime.Now.ToLongTimeString().Replace(":", "_");

                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                saveFileDialog.Title = @"Export Artist - Genre List";
                saveFileDialog.Filter = @"XML file(*.xml)|*.xml";
                saveFileDialog.FileName = string.Format("{0}.xml", string.Format("ArtistGenre_{0} {1}", date, time));

                DialogResult result = saveFileDialog.ShowDialog(this);

                if (result == DialogResult.OK)
                {
                    _artistGenreHelper.GetArtistGenreXmlDocument.Save(saveFileDialog.FileName, SaveOptions.OmitDuplicateNamespaces);
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("There was a problem exporting the ArtistGenre list\n\n{0}", ex.Message);

                MessageBox.Show(this, message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog.Title = @"Import Artist - Genre List";
                openFileDialog.Filter = @"XML file(*.xml)|*.xml";
                openFileDialog.FilterIndex = 1;
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                DialogResult result = openFileDialog.ShowDialog(this);

                if (result == DialogResult.OK)
                {
                    string msg;

                    XDocument doc = XDocument.Load(openFileDialog.FileName);

                    doc.Save(_artistGenreHelper.GetArtistGenreXmlPath);

                    _artistGenreHelper.OpenArtistGenreXml(out msg);

                    _artistGenres = _artistGenreHelper.GetAllArtistGenre();

                    SetObjects();
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("There was a problem importing the ArtistGenre list\n\n{0}", ex.Message);

                MessageBox.Show(this, message, @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
